## Accominotti and Flandreau 2008 WP

library(foreign) 
library(Amelia)

## Load original dataset
af2008 <- read.csv("AF2008 WP Rep Data.csv")
head(af2008)
dim(af2008)

## Drop ID vars
af2008$namei <- af2008$namej <-   NULL

## How many variables? 39: no reduction necessary
dim(af2008)

## Imputation
## What is average percentage of missing data?
NAs <- function(x) {
    as.vector(apply(x, 2, function(x) length(which(is.na(x)))))
    }
NAs(af2008)
mean(NAs(af2008)/nrow(af2008))*100

## Thus: 8 imputations

set.seed(02138)
af2008.out <- amelia(af2008, m = 8, cs = "codeij", ts = "year", polytime = 3, lags = c("ln_impij", "mfnij", "mfnout", "ymfnij"), empri = 0.01*nrow(af2008))

write.amelia(obj=af2008.out, file.stem = "AF2008 WP Imp Data", format = "dta", separate = FALSE)